package com.example.take_out_dish.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.take_out_dish.common.Result;
import com.example.take_out_dish.dto.CO;
import com.example.take_out_dish.dto.SC;
import com.example.take_out_dish.entity.Category;
import com.example.take_out_dish.entity.Dish;
import com.example.take_out_dish.entity.Setmeal;
import com.example.take_out_dish.entity.SetmealDish;
import com.example.take_out_dish.service.CategoryService;
import com.example.take_out_dish.service.SetmealDishService;
import com.example.take_out_dish.service.SetmealService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.websocket.server.PathParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 套餐 前端控制器
 * </p>
 *
 * @author wuyunbin
 * @since 2024-07-01
 */
@RestController
@Slf4j
@Tag(name = "套餐管理")
@RequestMapping("/setmeal")
public class SetmealController {
    @Resource
    private SetmealService setmealService;
    @Resource
    private CategoryService categoryService;
    @Resource
    private SetmealDishService setmealDishService;
    @GetMapping("page")
    public Result<IPage<SC>> page(int page, int pageSize, String name, String categoryId, Integer status) {
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.ne(Setmeal::getIsDeleted, 1);
        if (status != null) {

            wrapper.eq(Setmeal::getStatus, status);
        }
        wrapper.like(StrUtil.isNotBlank(name), Setmeal::getName, name);
        wrapper.eq(StrUtil.isNotBlank(categoryId), Setmeal::getCategoryId, categoryId);
        IPage<Setmeal> setmealPage = setmealService.page(new Page<>(page, pageSize), wrapper);
        log.info("categoryId:{}",categoryId);
        IPage<SC> scPage = new Page<>(setmealPage.getCurrent(), setmealPage.getSize(), setmealPage.getTotal());
        scPage.setRecords(new ArrayList<>());
        List<Setmeal> records = setmealPage.getRecords();
        for (Setmeal record : records) {
            SC sc = new SC();
            // 获取Category名称
            LambdaQueryWrapper<Category> cgWrapper = new LambdaQueryWrapper<>();
            cgWrapper.eq(Category::getId, record.getCategoryId());
            Category category = categoryService.getOne(cgWrapper);
            sc.setCategoryname(category.getName());

            // 获取setmealDish名称
            LambdaQueryWrapper<SetmealDish> sdWrapper = new LambdaQueryWrapper<>();
            sdWrapper.eq(SetmealDish::getSetmealId, record.getId());
            List<SetmealDish> Dishs = setmealDishService.list(sdWrapper);
            List<String> dishnames = Dishs.stream().map(SetmealDish::getName).collect(Collectors.toList());
            sc.setDishnames(dishnames);

            sc.setSetmeal(record);
            scPage.getRecords().add(sc);

        }
        return Result.success(scPage);
    }

    @GetMapping("{id}")
    public Result<Object> findById(@PathVariable Long  id) {
        Setmeal setmeal = setmealService.getById(id);
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> setmealDish = setmealDishService.list(queryWrapper);
        log.info("查询单个套餐详情",setmealDish);
        Map<String,Object> map = new HashMap<>();
        map.put("setmealDish",setmealDish);
        map.put("setmeal",setmeal);
//        this.setmealDishService.saveBatch()
        return Result.success(map);
    }

    /**
     * 添加套餐
     */
    @PostMapping
    public Result<Object> save(@RequestBody CO setmeal) {
        setmeal.setCreateUser("");
        setmeal.setUpdateUser("");
        setmeal.setCreateTime(new Date());
        setmeal.setUpdateTime(new Date());
        setmealService.save(setmeal);
        System.out.println("----------");
        for (SetmealDish setmealDish : setmeal.getSetmealDishes()) {
            setmealDish.setSetmealId(setmeal.getId());
            setmealDish.setCreateTime(new Date());
            setmealDish.setUpdateTime(new Date());
            setmealDish.setCreateUser("");
            setmealDish.setUpdateUser("");
            setmealDishService.save(setmealDish);
        }

//        System.out.println(setmeal);
//        System.out.println(dish);
//        SetmealDish setmealDish = new SetmealDish();
//        System.out.println("*------------");
//        System.out.println(setmeal);
//        System.out.println(setmeal.getSetmealDishes());;
//        setmealDish.setSetmealId(setmeal.getId());
//        setmealDish.setDishId(setmeal.getDish().getId());
//        setmealDish.setName(setmeal.getDish().getName());
//        setmealDish.setPrice(setmeal.getDish().getPrice());
//        setmealDish.setCopies(setmeal.getSetmealDishes();
//        setmealDishService.save()
        return Result.success();
    }

    @DeleteMapping
    public Result<Object> delete(@RequestParam String ids) {
        String[] idArray = ids.split(",");
        List<Long> idList = Arrays.stream(idArray)
                .map(Long::valueOf)
                .toList();

        // 执行删除操作
        idList.forEach(id -> {
            Setmeal setmeal = setmealService.getById(id);
            if (setmeal != null) {
                setmeal.setIsDeleted(1);
                setmealService.updateById(setmeal);
            }
        });
        return Result.success();
    }


    @PutMapping
    public Result<Object> update(@RequestBody CO setmeal) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("setmeal_id",setmeal.getId());
        setmealDishService.remove(queryWrapper);
        setmealService.updateById(setmeal);
        for (SetmealDish setmealDish : setmeal.getSetmealDishes()) {
            setmealDish.setSetmealId(setmeal.getId());
            setmealDish.setCreateTime(new Date());
            setmealDish.setUpdateTime(new Date());
            setmealDish.setCreateUser(setmeal.getCreateUser());
            setmealDish.setUpdateUser(setmeal.getCreateUser());
//            setmealService.updateById(setmeal);
            setmealDishService.save(setmealDish);
        }

        return Result.success();
    }

    @PostMapping("/status/{status}")
    public Result<Object> updatestuats(@PathVariable Integer status, @PathParam("id") String id) {
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Setmeal::getId, id);
        Setmeal one = setmealService.getOne(wrapper);
        one.setStatus(status);
        System.out.println("准备进行修改操作");
        setmealService.updateStatus(one);
        return Result.success();
    }


}
